#include "DDNumCreate.h"
#include "ConnectionPool.h"
#include "SqlQuery.h"
#include "Format.h"

DDNumCreate *DDNumCreate::globalInstance = new DDNumCreate();

DDNumCreate::DDNumCreate()
{
    // 初始化ID生成器，从数据库读取最大ID
    // 从数据库连接池获取一个mysql连接
    MYSQL *conn = ConnectionPool::getInstance()->getConnObj();
    SqlQuery query(conn);

    // 判断表是否是空的，因为select max(dd_num) from user 就算表为空，也会返回一行，获取空值时会报错
    string sql = "select count(*) from `group`";
    query.exec(sql);
    int rows = query.getRows();
    int count = atoi(query.getRes().front().front().data());
    if (count == 0)
        maxId = 10000000;
    else
    {
        // 查询最大ID
        sql = "select max(dd_num) from user";
        query.exec(sql);
        maxId = atoi(query.getRes().front().front().data());
    }

    // 回收数据库连接
    ConnectionPool::getInstance()->recycleConnObj(conn);
}

DDNumCreate::~DDNumCreate()
{
}

int DDNumCreate::createID()
{
    m_mutex.lock();
    int tmp = ++maxId;
    m_mutex.unlock();

    return tmp;
}
